package com.uobgroup.ews.uam.web.validation;

import org.springframework.stereotype.Component;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.uobgroup.ews.uam.core.domain.Profile;
import com.uobgroup.ews.uam.core.validator.JpaEntityValidator;
import com.uobgroup.ews.uam.web.dto.SearchCombinationMatrix;
import com.uobgroup.ews.uam.web.dto.SearchReference;
import com.uobgroup.ews.uam.web.dto.SearchRole;

@Component
public class ProfileValidator implements Validator {

   @Override
   public boolean supports(Class<?> clazz) {
      return Profile.class.getName().equals(clazz.getName()) || SearchRole.class.getName().equals(clazz.getName())
            || SearchCombinationMatrix.class.getName().equals(clazz.getName())
            || SearchReference.class.getName().equals(clazz.getName())
            || String.class.getName().equals(clazz.getName());
   }

   @Override
   public void validate(Object target, Errors errors) {
      if (target instanceof Profile) {
         Profile profile = (Profile) target;
         if(JpaEntityValidator.isNullConstraintViolated(profile, "name", false)){
            errors.rejectValue("name", "field_mandatory", new String[] { "Name" }, null);
         } else{
            if(JpaEntityValidator.isMaxLengthExceeded(profile, "name")){
               errors.rejectValue("name", "field_maxLength", new String[] {}, null);
            }
         }
         if(JpaEntityValidator.isMaxLengthExceeded(profile, "description")){
            errors.rejectValue("description", "field_maxLength", new String[] {}, null);
         }
         if (profile.getAccessToStaffName() == null || profile.getAccessToStaffName().trim().length() == 0) {
            errors.rejectValue("accessToStaff", "field_mandatory", new String[] { "Access To Staff" }, null);
         }
         if (profile.getRoles() == null || profile.getRoles().size() == 0) {
            errors.rejectValue("roles", "field_list_mandatory", new String[] { "Profile", "role" }, null);
         }
         if (profile.getSegments() == null || profile.getSegments().size() == 0) {
            errors.rejectValue("segments", "field_list_mandatory", new String[] { "Profile", "segment" }, null);
         }
         if (profile.getCombinationMatrices() == null || profile.getCombinationMatrices().size() == 0) {
            errors.rejectValue("combinationMatrices", "field_list_mandatory", new String[] { "Profile",
                  "combination matrix" }, null);
         }
      }
   }

}
